package net.ojbk.jiaofu.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.ojbk.jiaofu.service.TaskService;


/**
 * Servlet implementation class DownloadFileServlet
 */
@WebServlet("/DownloadExcelServlet")
public class DownloadExcelServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DownloadExcelServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
	    response.setCharacterEncoding("utf-8");
		// 前奏 ↑
		// 权限判断
		String pw = request.getParameter("pw"); // 常规判断
		String matchId = request.getParameter("matchId");
		
		HttpSession session=request.getSession();
		String userId=(String)session.getAttribute("myId");
		String taskId=(String)session.getAttribute("taskId");
				
		
/*		if (pw == null || pw.equals("") || matchId == null || matchId.equals(""))
			return ;*/
//		if (!BackstageService.checkMatchPw(matchId, pw)) // 不存在权限则 不响应
//			return ;
		if(userId==null||taskId==null) {
			return ;
		}
		
		// 开始 业务控制
		String filePath = TaskService.getExcelPath(userId,taskId);
		File file = new File(filePath);
		if (!file.exists()) {
			System.out.println("Excel不存在");
			return ;
		}
		FileInputStream fileInS = new FileInputStream(file);
		String filename=URLEncoder.encode(file.getName(),"utf-8"); //解决中文文件名下载后乱码的问题  
		
		byte[] b = new byte[fileInS.available()];
		fileInS.read(b);
		response.setHeader("Content-Disposition","attachment; filename="+filename+"");
		
		//获取响应报文输出流对象  
        ServletOutputStream  out =response.getOutputStream();  
        //输出  
        out.write(b);  
        out.flush();  
        out.close();
        
        
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
